import io
import os
import json
import pytesseract
from PIL import Image
from .result import result
from .parse import *
from .. import db
from ..models import *

# 解析验证码
# 根据观察，一般校园网的验证码是 4 位数，因此判断如果解析的结果不是 4 位数，则解析错误
def parse_captcha(captcha_file):
    try:
        img = Image.open(captcha_file)
        result = pytesseract.image_to_string(img)
        return None if len(result) != 4 else result
    except Exception as e:
        return None
    finally:# 清理资源
        if img:
            img.close()
        if captcha_file:
            captcha_file.close()

# 保存用户信息到数据库
# 首先查询数据库中是否已经存在当前用户数据，如果存在则先删除再保存，否则直接保存,下面的方法同理
def save_user_info(uid,json_data):
    try:
        userinfo = UserInfo.query.filter_by(uid=uid).first()
        print('save user info is:',userinfo)
        if userinfo != None:
            db.session.delete(userinfo)
            db.session.commit()

        data = json.loads(json_data)[0]
        item = UserInfo(uid=data.get('uid'),
                        name=data.get('name'),
                        grade=data.get('grade'),
                        college=data.get('college'),
                        specialty=data.get('specialty'))

        db.session.add(item)
        db.session.commit()
        return result(100)
    except Exception as e:
        print('save user info error:',e)
        return result(105)


# 保存上传的解析过的数据,保存成功返回 100，否则返回 105
def save_courses_text(uid,text):
    if uid == None or text == None:
        return result(111)
    return result(100) if save_courses(uid,json.loads(text)) else result(105)

# 解析原始 Html 网页，保存，并返回
def save_courses_html(uid,html):
    if uid == None or html == None:
        return result(111)
    json_list = parse_courses_html(uid,html)

    if json_list != None and isinstance(json_list,list):
        return result(100,json_list) if save_courses(uid,json_list) else result(105)
    else:
        return result(112)

# 保存课表到数据库,保存之前先查询是否已经有数据了，如果已经有了，则先删除再存
# TODO 后期可以考虑从这里入手做更新提醒，比如有新增的数据，则标记出来，提示用户有新增的数据
def save_courses(uid,json_list):
    try:
        courses = Courses.query.filter_by(uid=uid).all()
        if len(courses) > 0:
            for item in courses:
                db.session.delete(item)
            db.session.commit()

        for item in json_list:
            course = Courses(uid=item.get('uid'),
                            schoolYear=item.get('schoolYear'),
                            term=item.get('term'),
                            cid=item.get('cid'),
                            cname=item.get('cname'),
                            period=item.get('period'),
                            credit=item.get('credit'),
                            startSection=item.get('startSection'),
                            endSection=item.get('endSection'),
                            startWeek=item.get('startWeek'),
                            endWeek=item.get('endWeek'),
                            dayOfWeek=item.get('dayOfWeek'),
                            classroom=item.get('classroom'),
                            teacher=item.get('teacher'),
                            campus=item.get('campus'),
                            studyType=item.get('studyType'),
                            studyMethod=item.get('studyMethod'))
            db.session.add(course)
        db.session.commit()
        return True
    except Exception as e:
        print('save courses error:',e)
        return False

# 保存已经解析过的成绩列表
def save_scores_text(uid,text):
    if uid == None or text == None:
        return result(111)
    return result(100) if save_scores(uid,json.loads(text)) else result(105)

# 首先对原始成绩网页解析，解析成列表，保存,返回
def save_scores_html(uid,html):
    if uid == None or html == None:
        return result(111)
    json_list = parse_scores_html(uid,html)

    if json_list != None and isinstance(json_list,list):
        return result(100,json_list) if save_scores(uid,json_list) else result(105)
    else:
        return result(112)

# 保存成绩信息到数据库
def save_scores(uid,json_list):
    try:
        scores = Scores.query.filter_by(uid=uid).all()
        if len(scores) > 0:
            for item in scores:
                db.session.delete(item)
            db.session.commit()

        for item in json_list:
            score = Scores(uid=item.get('uid'),
                            schoolYear=item.get('schoolYear'),
                            term=item.get('term'),
                            cid=item.get('cid'),
                            cname=item.get('cname'),
                            type=item.get('type'),
                            property=item.get('property'),
                            credit=item.get('credit'),
                            score=item.get('score'),
                            studyMethod=item.get('studyMethod'))

            db.session.add(score)
        db.session.commit()
        return True
    except Exception as e:
        print('save scores error:',e)
        return False



# 保存已经解析过的考试列表
def save_exams_text(uid,text):
    if uid == None or text == None:
        return result(111)
    return result(100) if save_exams(uid,json.loads(text)) else result(105)

# 首先对原始考试网页解析，解析成列表，保存
def save_exams_html(uid,html):
    if uid == None or html == None:
        return result(111)
    json_list = parse_exams_html(uid,html)

    if json_list != None and isinstance(json_list,list):
        return result(100,json_list) if save_exams(uid,json_list) else result(105)
    else:
        return result(112)


# 保存考试信息
def save_exams(uid,json_list):
    try:
        exams = Exams.query.filter_by(uid=uid).all()
        if len(exams) > 0:
            for item in exams:
                db.session.delete(item)
            db.session.commit()
        for item in json_list:
            exam = Exams(uid=item.get('uid'),
                            cid=item.get('cid'),
                            cname=item.get('cname'),
                            property=item.get('property'),
                            teacher=item.get('teacher'),
                            credit=item.get('credit'),
                            date=item.get('date'),
                            time=item.get('time'),
                            classroom=item.get('classroom'),
                            type=item.get('type'),
                            method=item.get('method'),
                            status=item.get('status'))
            db.session.add(exam)
        db.session.commit()
        return True
    except Exception as e:
        print('save exams error:',e)
        return False

# 检查客户端是否有更新
def check_client_update(version_code):
    try:
        basedir=os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
        with open(basedir+'/appConfig.json','r') as config:
            data = json.loads(config.read()).get('version')
            new_version_code = data.get('versionCode')
            if new_version_code > version_code:# 如果最新版本号大于当前版本号，则说明有新版本
                return result(100,[{'hasNew':1,'versionCode':new_version_code,'versionName':data.get('versionName'),'description':data.get('description'),'url':data.get('url')}])
            else:
                return result(100,[{'hasNew':0,'versionCode':'','versionName':'','description':'','url':''}])
    except Exception as e:
        print('check_client_update error:',e)
        return result(105)

# 获取启动页图片链接
def request_launch_img():
    try:
        basedir=os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
        with open(basedir+'/appConfig.json','r') as config:
            data = json.loads(config.read()).get('launch')
            return result(100,[{'imgUrl':data.get('imgUrl')}])
    except Exception as e:
        print('request launch_img error:',e)
        return result(105)
